package com.ssh.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ssh.entity.User;
import com.ssh.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/login.do")
	public String userLogin(String userName, String password, HttpServletRequest req){
		if(userName=="" || password==""){
			req.setAttribute("loginError", "用户名和密码不能为空！");
			return "login";
		}else if(userService.loadUserByName(userName, password) == null){
			req.setAttribute("loginError", "用户名或者密码错误，请重新输入！");
			return "login";
		}else {
			req.getSession().setAttribute("LoginUserName", userName);
			return "../index";
		}
		
		/*else if(userService.loadUserByName(userName,userPass)== null) {
				req.getSession().setAttribute("loginError", "用户名或密码错误,请重新输入");
				return null;
		}else{
				user =userService.loadUserByName(userName,userPass);
				req.getSession().setAttribute("User", user);
				return "index";				
		}*/
	}
	
	@RequestMapping(value="/reg.do")
	public String userRegister(String userName, String phone,String email, String password, String userPass2, HttpServletRequest req){
		try {
			req.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(userName=="" || phone=="" || email=="" || password=="" || userPass2==""){
			req.setAttribute("registerError", "输入不能为空！");
			return "register";
		}
		if(password.equals(userPass2)){
			User user = new User();
			user.setEmail(email);
			user.setPassword(password);
			user.setPhone(phone);
			user.setUserName(userName);
			int i = userService.userRegister(user);
			if(i==1){
				return "../index";
			}else{
				req.setAttribute("registerError", "用户名已被占用，请重新输入！");
				return "register";
			}
		}else{
			req.setAttribute("registerError", "确认密码输入不正确！");
			return "register";
		}
	}
	
	@RequestMapping(value="/exit.do")
	public String exitUser(HttpServletRequest req){
		try {
			req.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		req.getSession().invalidate();
		return "../index";
	}
}
